﻿using NewRen.Helpers;
using NewRen.Models;
using NewRen.Models.ViewModel;
using NewRen.Schemas;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NewRen.Areas.Admin.Controllers
{
    public class BusinessController : BaseController
    {
        // GET: Admin/Business
        public ActionResult Index(string key, DateTime? Begin, DateTime? End, int p = 0)
        {
            IEnumerable<Business> query = db.Businesses.AsEnumerable();
            if (!string.IsNullOrEmpty(key))
            {
                query = query.Where(c => c.BusinessName.Contains(key));
            }
            if (Begin.HasValue)
            {
                query = query.Where(c => c.AddTime >= Begin);
            }
            if (End.HasValue)
            {
                query = query.Where(c => c.AddTime <= End);
            }
            query = query.OrderByDescending(x => x.AddTime);
            ViewBag.PageInfo = PagerHelper.Do(ref query, 50, p);
            return View(query);
        }

        [HttpGet]
        public ActionResult Add()
        {
            var industries = db.Industries.ToList();
            var cities = db.Cities.ToList();
            ViewBag.Industries = industries;
            ViewBag.Cities = cities;
            return View();
        }

        #region 增加商家
        /// <summary>
        /// 增加商家
        /// </summary>
        /// <param name="model"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Add(Business model, HttpPostedFileBase file)
        {
            var industries = db.Industries.ToList();
            var cities = db.Cities.ToList();
            ViewBag.Industries = industries;
            ViewBag.Cities = cities;
            if (ModelState.IsValid)
            {
                if (file != null)
                {
                    System.IO.Stream stream = file.InputStream;
                    byte[] buffer = new byte[stream.Length];
                    stream.Read(buffer, 0, (int)stream.Length);
                    stream.Close();
                    model.Picture = buffer;
                }
                model.LoginPassword = Helpers.Encryt.GetMD5(model.LoginPassword);
                model.AddTime = DateTime.Now;
                db.Businesses.Add(model);
                db.SaveChanges();
                return Redirect("/Admin/Business/Index");
            }
            else
            {
                ModelState.AddModelError("", "商家信息填写错误！");
            }
            return View();
        }

        #endregion


        #region 删除商家
        /// <summary>
        /// 删除商家
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateSID]
        public ActionResult Delete(int id)
        {
            try
            {
                var business = db.Businesses.Find(id);
                db.Businesses.Remove(business);
                db.SaveChanges();
                return Content("ok");
            }
            catch
            {
                return Content("fail");
            }
        }
        #endregion

        #region 商家显示
        /// <summary>
        ///  商家显示
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Show(int id)
        {
            var business = db.Businesses.Find(id);
            ViewBag.Business = business;
            return View();
        }
        #endregion


        #region 图标显示
        /// <summary>
        /// 图标显示
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ShowPicture(int id)
        {
            Business business = new Business();
            business = db.Businesses.Find(id);
            return File(business.Picture, "image/jpg");
        }
        #endregion

        /// <summary>
        /// 编辑商家
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Edit(int id)
        {
            Business business = new Business();
            business = db.Businesses.Find(id);
            ViewBag.Business = business;
            return View();
        }


        #region 修改商家信息
        /// <summary>
        /// 修改商家信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Business model, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                var business = db.Businesses.Find(model.ID);
                if (file != null)
                {
                    System.IO.Stream stream = file.InputStream;
                    byte[] buffer = new byte[stream.Length];
                    stream.Read(buffer, 0, (int)stream.Length);
                    stream.Close();
                    business.Picture = buffer;
                }
                business.BusinessName = model.BusinessName;
                business.Description = model.Description;
                business.City = model.City;
                business.Phone = model.Phone;
                business.LoginName = model.LoginName;
                business.LoginPassword = Helpers.Encryt.GetMD5(model.LoginPassword);
                business.Email = model.Email;
                business.WhatApp = model.WhatApp;
                business.Weibo = model.Weibo;
                business.Address = model.Address;
                business.Priority = model.Priority;
                db.SaveChanges();
                return Redirect("/Admin/Business/Index");
            }
            else
            {
                ModelState.AddModelError("", "商家信息填写错误！");
            }
            return View();
        }

        #endregion


        #region 显示产品
        /// <summary>
        /// 显示产品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Products(int id)
        {
            List<Product> _products = db.Products.Where(p => p.BusinessID == id).ToList();
            List<vProduct> products = new List<vProduct>();
            foreach (var item in _products)
            {
                products.Add(new vProduct(item));
            }
            return View(products);
        }
        #endregion


        #region 修改优先级
        /// <summary>
        /// 修改优先级
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult PriorityEdit(int id)
        {
            var business = db.Businesses.Find(id);
            return View(business);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult PriorityEdit(int ID, int Priority)
        {
            var business = db.Businesses.Find(ID);
            if (ModelState.IsValid)
            {
                try
                {
                    business.Priority = Priority;
                    db.SaveChanges();
                    return Redirect("/Admin/UserGroup/Index");
                }
                catch
                {
                    ModelState.AddModelError("", "修改失败，请重试！");
                }
            }
            else
            {
                ModelState.AddModelError("", "你输入的信息不正确，请重新输入！");
            }
            return View(business);
        }
        #endregion

        #region 商家认证
        /// <summary>
        /// 商家认证
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult VerifyEdit(int id)
        {
            var business = db.Businesses.Find(id);
            return View(business);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult VerifyEdit(int ID, bool IsVerifed)
        {
            var business = db.Businesses.Find(ID);
            try
            {
                business.IsVerified = IsVerifed;
                db.SaveChanges();
                return Redirect("/Admin/Business/Index");
            }
            catch
            {
                ModelState.AddModelError("", "修改出错，请重试！");
                return View(business);
            }

        }
        #endregion


        /// <summary>
        /// 商家信息统计
        /// </summary>
        /// <returns></returns>
        public ActionResult Stat()
        {
            var now = DateTime.Now;
            var total = db.Businesses.Count();
            var todayTotal = db.Businesses.Where(b => b.AddTime.Year == now.Year && b.AddTime.Year == now.Month && b.AddTime.Day == now.Day).Count();
            ViewBag.Total = total;
            ViewBag.TodayTotal = todayTotal;
            return View();
        }

        /// <summary>
        /// 设置显示状态
        /// </summary>
        /// <returns></returns>
        public ActionResult SetShow(int id)
        {
            try
            {
                var business = db.Businesses.Find(id);
                if (business.IsShow)
                {
                    business.IsShow = false;
                }
                else
                {
                    business.IsShow = true;
                }
                db.SaveChanges();
                return Redirect("/Admin/Business/Index");
            }
            catch
            {
                return Redirect("/Admin/Shared/Info?msg=修改牛人显示信息失败");
            }
        }
    }
}